package mechanism;

import java.util.concurrent.TimeUnit;

//Broken! - How long would you expect this program to run?
public class ThreadApp {
	private static boolean stopRequested;
	//private static volatile long time; // 统计由设置停止到线程真正停止的时间 (为0呀？whywhywhy)
	public static void main(String[] args) throws InterruptedException {
		Thread backgroundThread = new Thread(new Runnable() {
			public void run() {
				int i = 0;
				while (!stopRequested)
				{
					i++;
				}
				System.out.println(i);
				System.out.println("stopped");
				//System.out.println(System.currentTimeMillis() - time);
			}
		});
		backgroundThread.start();
		TimeUnit.SECONDS.sleep(1);
		stopRequested = true;
		//time = System.currentTimeMillis();
	}
}

//Properly synchronized cooperative thread termination
class ThreadApp1 {
	private static boolean requestStoped;
	private synchronized static boolean isRequestStopped() {
		return requestStoped;
	}
	private synchronized static void stopRequest() {
		requestStoped = true;
	}
	
	public static void main(String[] args) throws InterruptedException {
		Thread backgroundThread = new Thread(new Runnable() {
			public void run() {
				int i = 0;
				while (!isRequestStopped())
				{
					i++;
				}
				System.out.println(i);
				System.out.println("stopped");
			}
		});
		backgroundThread.start();
		TimeUnit.SECONDS.sleep(1);
		stopRequest();
	}	
}

//Cooperative thread termination with a volatile field
class ThreadApp2 {
	private static volatile boolean requestStopped;
	public static void main(String[] args) throws Exception{
		Thread backgroundThread = new Thread(
				new Runnable(){
					public void run() {
						int i=0;
						while(!requestStopped){
							i++;
						}
						System.out.println(i);
						System.out.println("stopped");
					}
				}
		);
		backgroundThread.start();
		TimeUnit.SECONDS.sleep(1);
		requestStopped = true;
	}
}

